package com.gitee.demo1;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author worlt
 * @Date 2025/1/14 下午7:33
 */

@RestController
@RequestMapping("/api/v1")
@Transactional(rollbackFor = Exception.class)
public class UploadController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @PostMapping("/uploadImg")
    public Result uploadImg(@RequestParam("file") MultipartFile file) throws Exception {
        String originalFileName = file.getOriginalFilename();
        if (originalFileName == null) {
            return Result.fail(Result.IMG_EXIST_ERROR, "文件名不能为空");
        }

        String targetDir = GiteeImgBed.getPath() + originalFileName;

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("access_token", GiteeImgBed.getAccessToken());
        jsonBody.put("message", GiteeImgBed.ADD_MESSAGE);
        jsonBody.put("content", Base64.encode(file.getBytes()));

        String requestUrl = String.format(
                GiteeImgBed.CREATE_REPOS_URL,
                GiteeImgBed.getOwner(),
                GiteeImgBed.getRepoName(),
                targetDir
        );

        String resultJson = HttpRequest.post(requestUrl)
                .header("Content-Type", "application/json")
                .body(jsonBody.toString())
                .execute()
                .body();

        JSONObject response = JSONUtil.parseObj(resultJson);
        if (response != null && response.get("content") != null) {
            JSONObject content = response.getJSONObject("content");
            return Result.success(content.getStr("download_url"));
        }
        return Result.fail(Result.SERVE_ERROR, "上传失败");
    }

    @DeleteMapping("/delImg")
    public Result delImg(@RequestParam String imgPath) {
        try {
            String path = imgPath.split("raw/[^/]+/")[1];
            String getUrl = String.format(
                    GiteeImgBed.GET_IMG_URL,
                    GiteeImgBed.getOwner(),
                    GiteeImgBed.getRepoName(),
                    path
            ) + "?access_token=" + GiteeImgBed.getAccessToken();

            String getResponse = HttpRequest.get(getUrl).execute().body();
            JSONObject fileInfo = JSONUtil.parseObj(getResponse);
            if (fileInfo == null || fileInfo.get("sha") == null) {
                return Result.fail(Result.IMG_EXIST_ERROR, "文件不存在");
            }

            String delUrl = String.format(
                    GiteeImgBed.DEL_IMG_URL,
                    GiteeImgBed.getOwner(),
                    GiteeImgBed.getRepoName(),
                    path
            );

            JSONObject delBody = new JSONObject();
            delBody.put("access_token", GiteeImgBed.getAccessToken());
            delBody.put("sha", fileInfo.getStr("sha"));
            delBody.put("message", GiteeImgBed.DEl_MESSAGE);

            String delResponse = HttpRequest.delete(delUrl)
                    .header("Content-Type", "application/json")
                    .body(delBody.toString())
                    .execute()
                    .body();

            return JSONUtil.parseObj(delResponse).get("commit") != null ?
                    Result.success("删除成功") :
                    Result.fail(Result.SERVE_ERROR, "删除失败");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return Result.fail(Result.SERVE_ERROR, "删除失败");
        }
    }
}